﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using TaskManager;

namespace SimpleHttpServer
{
    public class HttpService
    {
        private HttpListener httpListener;
        private WorkerCenter WorkerCenter { get; set; }

        public string ListenUrl { get; set; } = "+:80";

        public HttpService() : this(Environment.ProcessorCount * 5)
        {

        }

        public HttpService(int tCount)
        {
            WorkerCenter = new WorkerCenter(tCount);
        }

        public void StartAysn()
        {
            Task.Factory.StartNew(() => { Start(); });
        }

        public void Start()
        {
            if (WorkerCenter == null)
                throw new Exception("not found work center");

            httpListener = new HttpListener();

            if (!string.IsNullOrEmpty(ListenUrl))
                httpListener.Prefixes.Add(ListenUrl);

            httpListener.Start();

            while (true)
            {
                try
                {
                    var context = httpListener.GetContext();
                    this.WorkerCenter.PublishJob(new HttpHandleJob { Context = context });
                }
                catch (Exception ex)
                {
                    break;
                }
            }

            // http server stop
        }

        public void Stop()
        {
            httpListener?.Stop();
        }
    }
}
